import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Descriptions, Drawer, Space } from 'antd';

import Dict from '@/components/dict';
import Text from '@/components/text';

import { LevelObj, MethodObj } from '@/enum/log';
import { apiLogGet } from '@/services/base/quanxianmokuaixitongjiekourizhijiekou';
import { formatDate, formatValue } from '@/utils';
import JsonView from '@uiw/react-json-view';

import { BizObject } from './index';

export type DetailRef = {
  open: (arg: { rowData: BizObject }) => void;
};

export type DetailProps = {};

const Detail: React.ForwardRefRenderFunction<DetailRef, DetailProps> = (_, ref) => {
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<DetailRef['open']>[0]>();
  const detail = useRequest(
    async (query: ArgumentsType<typeof apiLogGet>[0]) => {
      const res = await apiLogGet(query, {
        tupleResponse: false
      });

      return res.data;
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        detail.run({ id: arg.rowData.id as unknown as string });
      }
    };
  });

  const onCancel = () => {
    setOpen(false);
  };

  return (
    <Drawer
      title="详情"
      extra={
        <Space>
          <Button onClick={onCancel}>关闭</Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Descriptions size="small" column={2} bordered title="登录信息">
        <Descriptions.Item label="id">
          {formatValue((detail.data || args?.rowData)?.id)}
        </Descriptions.Item>
        <Descriptions.Item label="请求接口地址">
          {formatValue((detail.data || args?.rowData)?.reqApi)}
        </Descriptions.Item>
        <Descriptions.Item label="请求类型" span={2}>
          {formatValue(MethodObj.get((detail.data || args?.rowData)?.reqType as string)?.text)}
        </Descriptions.Item>
        <Descriptions.Item label="请求header" span={2}>
          <JsonView
            collapsed
            displayObjectSize={false}
            displayDataTypes={false}
            enableClipboard={false}
            value={JSON.parse((detail.data || args?.rowData)?.reqHeader || '{}')}
          />
        </Descriptions.Item>
        <Descriptions.Item label="请求参数" span={2}>
          <JsonView
            collapsed
            displayObjectSize={false}
            displayDataTypes={false}
            enableClipboard={false}
            value={JSON.parse((detail.data || args?.rowData)?.reqParam || '{}')}
          />
        </Descriptions.Item>
        <Descriptions.Item label="返回结果消息" span={2}>
          <JsonView
            collapsed
            displayObjectSize={false}
            displayDataTypes={false}
            enableClipboard={false}
            value={JSON.parse((detail.data || args?.rowData)?.resStr || '{}')}
          />
          <Descriptions.Item label="返回结果状态">
            {formatValue((detail.data || args?.rowData)?.resStatus)}
          </Descriptions.Item>
        </Descriptions.Item>
        <Descriptions.Item label="日志级别">
          {formatValue(LevelObj.get((detail.data || args?.rowData)?.logLevel as number)?.text)}
        </Descriptions.Item>
        <Descriptions.Item label="日志说明">
          {formatValue((detail.data || args?.rowData)?.logExplain)}
        </Descriptions.Item>
        <Descriptions.Item label="请求token">
          {formatValue((detail.data || args?.rowData)?.reqToken)}
        </Descriptions.Item>
        <Descriptions.Item label="请求开始时间">
          {formatDate((detail.data || args?.rowData)?.startTime)}
        </Descriptions.Item>
        <Descriptions.Item label="请求结束时间">
          {formatDate((detail.data || args?.rowData)?.endTime)}
        </Descriptions.Item>
        <Descriptions.Item label="请求结束时间">
          {formatDate((detail.data || args?.rowData)?.createTime)}
        </Descriptions.Item>
        <Descriptions.Item label="请求耗时">
          <Text>
            {formatValue((((detail.data || args?.rowData)?.costTime || 0) / 1000).toFixed(3))}s
          </Text>
        </Descriptions.Item>
      </Descriptions>

      <div style={{ height: 40 }}></div>

      <Descriptions size="small" column={2} bordered title="客户端信息">
        <Descriptions.Item label="请求ip">
          {formatValue((detail.data || args?.rowData)?.reqIp)}
        </Descriptions.Item>
        <Descriptions.Item label="请求城市">
          {formatValue((detail.data || args?.rowData)?.reqCity)}
        </Descriptions.Item>
        <Descriptions.Item label="请求客户端类型">
          <Dict dicCode="clientType" value={(detail.data || args?.rowData)?.clientType} />
        </Descriptions.Item>
        <Descriptions.Item label="操作系统">
          {(detail.data || args?.rowData)?.systemName}
        </Descriptions.Item>
        <Descriptions.Item label="浏览器">
          {(detail.data || args?.rowData)?.browser}
        </Descriptions.Item>
      </Descriptions>

      <div style={{ height: 40 }}></div>

      <Descriptions size="small" column={2} bordered title="用户信息">
        <Descriptions.Item label="用户id">
          {formatValue((detail.data || args?.rowData)?.userId)}
        </Descriptions.Item>
        <Descriptions.Item label="请求用户名">
          {formatValue((detail.data || args?.rowData)?.username)}
        </Descriptions.Item>
        <Descriptions.Item label="请求用户姓名">
          {formatValue((detail.data || args?.rowData)?.fullName)}
        </Descriptions.Item>
        <Descriptions.Item label="请求用户类型">
          <Dict dicCode="userType" value={(detail.data || args?.rowData)?.userType} />
        </Descriptions.Item>
      </Descriptions>
    </Drawer>
  );
};

export default forwardRef(Detail);
